package mybatis;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisXMLDemo {

    public static void main(String[] args) {
        User user = new User();
        user.setId(1);
        user.setName("Jack");
        int insertNum = insert(user);
        System.out.println(insertNum);
        String name = selectNameById(1);
        System.out.println(name);
    }




    private static Integer insert(User user){
        int insertNum = 0;
        try (SqlSession session = openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            insertNum = mapper.insert(user);
            session.commit();
        }
        return insertNum;
    }

    private static String selectNameById(Integer id){
        String name = null;
        try (SqlSession session = openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            name = mapper.selectNameById(id);
        }
        return name;
    }




    private static SqlSession openSession(){
        SqlSession sqlSession = null;
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            sqlSession = sqlSessionFactory.openSession();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sqlSession;
    }

}
